import { createRouter, createWebHistory } from "vue-router";
import { useUserStore } from '/src/store/userStore.js';
import Parent from "../components/Parent.vue";
import Child from "../components/Child.vue";

const routes = [
  {path: "/",name: "Index",title:'首页',component: () => import("../views/index/index.vue"),},
  {path: "/mall",name: "Mall",title:'商城',component: () => import("../views/mall/index.vue"),},
  {path: "/login",name: "Login",title:'登录',component: () => import("../views/login/index.vue"),},
  {path: "/reg",name: "Reg",title:'注册',component: () => import("../views/reg/index.vue"),},
  {path: "/person",name: "Person",title:'个人中心',component: () => import("../views/person/index.vue"),},
  {path: "/parent",name: "Parent",title:'父组件',component: Parent,children:[
    {path: "child",name: "Child",title:'子组件',component: Child}
  ]},
  {path: "/user",name: "User",title:'用户',component: () => import("../views/user/index.vue"),},
  {path: "/user/list",name: "UserList",title:'用户列表',component: () => import("../components/User.vue"),},
  ]

  
const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.addRoute({
   path:'/user/:id',
   name:'UserDetail',
   component: () => import('../components/UserDetail.vue'),
}
)

router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  
  // 初始化用户状态
  userStore.initialize();
  
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    // 需要登录但未登录，重定向到登录页
    next({ name: 'Login' });
  } else if ((to.name === 'Login' || to.name === 'Reg') && userStore.isLoggedIn) {
    // 已登录但尝试访问登录/注册页，重定向到首页
    next({ name: 'Index' });
  } else {
    // 其他情况正常导航
    next();
  }
});

export default router;